package zoran.wang.tools;

import zoran.wang.tree.Node;

import java.util.Random;

/**
 * 随机多叉树生成器
 *
 * @author DeepSeek
 * @time 2025-04-12-14:14
 */
public class RandomMultiwayTreeGenerator {

    private Random random;
    private int minChildren;
    private int maxChildren;

    public RandomMultiwayTreeGenerator(int minChildren, int maxChildren) {
        if (minChildren < 0 || maxChildren < minChildren) {
            throw new IllegalArgumentException("Invalid children range");
        }
        this.random = new Random();
        this.minChildren = minChildren;
        this.maxChildren = maxChildren;
    }

    // 生成随机多叉树
    public Node generateTree(int totalLevels) {
        if (totalLevels <= 0) {
            return null;
        }

        // 根节点的值随机生成
        Node root = new Node(random.nextInt());
        generateChildren(root, totalLevels - 1);
        return root;
    }

    // 递归生成子节点
    private void generateChildren(Node node, int remainingLevels) {
        if (remainingLevels <= 0) {
            return;
        }

        // 随机决定子节点数量
        int childCount = minChildren + (maxChildren > minChildren ? random.nextInt(maxChildren - minChildren + 1) : 0);

        for (int i = 0; i < childCount; i++) {
            Node child = new Node(random.nextInt());
            node.children.add(child);
            generateChildren(child, remainingLevels - 1);
        }
    }

    // 打印树结构
    public static void printTree(Node root) {
        printTreeHelper(root, 0);
    }

    private static void printTreeHelper(Node node, int level) {
        if (node == null) {
            return;
        }

        StringBuilder indent = new StringBuilder();
        for (int i = 0; i < level; i++) {
            indent.append("  ");
        }

        System.out.println(indent + "└─ " + node.val);

        for (Node child : node.children) {
            printTreeHelper(child, level + 1);
        }
    }

    // 生成并打印
    public static Node generatorAndPrint(int minChildren, int maxChildren, int totalLevels) {

        RandomMultiwayTreeGenerator generator = new RandomMultiwayTreeGenerator(minChildren, maxChildren);
        Node tree = generator.generateTree(totalLevels);

        System.out.println("Generated Random Multiway Tree:");
        printTree(tree);

        return tree;
    }
}